package com.yups.dao;
import com.yups.model.*;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;

/**
 * 预约数据操作类
 *
 * @author 于鹏生
 */
public class BookDao extends BaseDao {
	public int getMaxId() {
		String sql = "select max(id) maxid from book";
		try {
			return queryRunner.query(sql, rs -> {
				if (rs.next()) {
					return rs.getInt("maxid");
				}
				return -1;
			});
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return -1;
	}

	public boolean addBook(Book book) {
		String sql = "insert into book"
				+ "  (id, service_id, user_id, booktime, price, message)"
				+ " values"
				+ " (?, ?, ?, ?, ?, ?)";
		try {
			return queryRunner.execute(sql,
					book.getId(),
					book.getService().getId(),
					book.getUser().getId(),
					book.getBookTime(),
					book.getPrice(),
					book.getMessage()
			) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public List<Book> getBook() {
		String sql = "select B.id bid, B.service_id bserid, B.user_id buseid,"
				+ " B.booktime bbooktime, B.price bprice, B.message bmessage,"
				+ " S.subject ssubject,S.photo sphoto,S.coverpath scoverpath,"
				+ " S.price sprice,S.message smessage,S.recommend srecommend,"
				+ " S.detail sdetail,S.coach_id scoach_id,S.servicetype_id stid,"
				+ " C.company ccompany,C.photo cphoto,C.avatar cavatar,"
				+ " C.nickname cnickname,C.price cprice,C.message cmessage,"
				+ " ST.icon sticon,ST.title sttitle"
				+ " from book B"
				+ " left join service S on B.service_id = S.id"
				+ " left join coach C on S.coach_id = C.id"
				+ " left join servicetype ST on S.servicetype_id = ST.id";
		try {
			return queryRunner.query(sql, rs -> {
				List<Book> books = new LinkedList<Book>();
				while (rs.next()) {
					Timestamp bookTime;
					books.add(new Book(
							rs.getInt("bid"),
							new Service(
									rs.getInt("buseid"),
									rs.getString("ssubject"),
									rs.getString("sphoto"),
									rs.getString("scoverpath"),
									rs.getDouble("sprice"),
									rs.getString("smessage"),
									rs.getString("srecommend"),
									rs.getString("sdetail"),
									new Coach(
											rs.getInt("scoach_id"),
											rs.getString("ccompany"),
											rs.getString("cphoto"),
											rs.getString("cavatar"),
											rs.getString("cnickname"),
											rs.getDouble("cprice"),
											rs.getString("cmessage"),
											//TODO 这里 SQL 语句有问题
											rs.getDouble(""),
											rs.getDouble("")
									),
									new ServiceType(
											rs.getInt("stid"),
											rs.getString("sticon"),
											rs.getString("sttitle")
									)
							),
							new User(rs.getInt("buseid")),
							rs.getTimestamp("bbooktime"),
							rs.getLong("bprice"),
							rs.getString("bmessage")
					));
				}
				return books;
			});
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}
